package com.lnsoft.dqfs.server;

import com.lnsoft.dqfs.server.handle.HandleFactory;
import com.lnsoft.dqfs.server.handle.codec.Frame;
import com.lnsoft.dqfs.server.util.UpgradePackageCache;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class DqfsChannelInitializer extends ChannelInitializer<SocketChannel> {

    private static final Logger logger = LoggerFactory.getLogger(DqfsChannelInitializer.class);

    @Autowired
    private HandleFactory handleFactory;

    @Value("${netty.server.read_timeout}")
    private int readTimeOut;

    @Autowired
    private UpgradePackageCache upgradePackageCache;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        // 复用这个对象
       // ch.attr(AttributeKey.valueOf("frame")).set(new Frame());

        Frame frame = new Frame();
        frame.setServerPort(ch.localAddress().getPort());
        logger.debug("NioServiceSocketChannle#initChannel");
        ChannelPipeline pipeline = ch.pipeline();
        // 心跳检测
        pipeline.addLast("IdleStateHandler",new IdleStateHandler(readTimeOut,0,0));
        // 心跳检测自定义处理
        pipeline.addLast("HeartBeatServerHandle",handleFactory.createHeartBeatServerHandle(frame));

        pipeline.addLast("Dqfs101Decoder",handleFactory.createDqfs101Decoder(frame, upgradePackageCache));
        pipeline.addLast("Dqfs101Encoder",handleFactory.createDqfs101Encoder());

        pipeline.addLast("DqfsChannelHandle",handleFactory.createDqfsChannelHandle(frame));
    }
}